<!--字典类型-->
<script setup lang="ts">
import {
  getDictTypePage,
  getDictTypeForm,
  addDictType,
  updateDictType,
  deleteDictTypes,
} from "@/api/dict";

import { DictTypePageVO, DictTypeQuery, DictTypeForm } from "@/api/dict/types";

defineOptions({
  name: "merchantList",
  inheritAttrs: false,
});

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<DictTypeQuery>({
  pageNum: 1,
  pageSize: 10,
});

const dictTypeList = ref<DictTypePageVO[]>();

const dialog = reactive({
  title: "",
  visible: false,
});

const formData = reactive<DictTypeForm>({
  status: 1,
});

const rules = reactive({
  name: [{ required: true, message: "请输入字典类型名称", trigger: "blur" }],
  code: [{ required: true, message: "请输入字典类型编码", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getDictTypePage(queryParams)
    .then(({ data }) => {
      dictTypeList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

/**
 * 打开字典类型表单弹窗
 *
 * @param dicTypeId 字典类型ID
 */
function openDialog(dicTypeId?: number) {
  dialog.visible = true;
  if (dicTypeId) {
    dialog.title = "修改字典类型";
    getDictTypeForm(dicTypeId).then(({ data }) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增字典类型";
  }
}

/** 字典类型表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const dictTypeId = formData.id;
      if (dictTypeId) {
        updateDictType(dictTypeId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        addDictType(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭字典类型弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置字典类型表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.id = undefined;
  formData.status = 1;
}

/** 删除字典类型 */
function handleDelete(dictTypeId?: number) {
  const dictTypeIds = [dictTypeId || ids.value].join(",");
  if (!dictTypeIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deleteDictTypes(dictTypeIds).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

const dictDataDialog = reactive({
  title: "",
  visible: false,
});

const selectedDictType = reactive({ typeCode: "", typeName: "" }); // 当前选中的字典类型

/** 打开字典数据弹窗 */
function openDictDialog(row: DictTypePageVO) {
  dictDataDialog.visible = true;
  dictDataDialog.title = "【" + row.name + "】字典数据";

  selectedDictType.typeCode = row.code;
  selectedDictType.typeName = row.name;
}

/**  关闭字典数据弹窗 */
function closeDictDialog() {
  dictDataDialog.visible = false;
}

onMounted(() => {
  handleQuery();
});


const value = ref('')
const options = [
  {
    label: '启用',
    value: '1',
  },
  {
    label: '禁用',
    value: '2',
  },
]


/* 静态表格字段 */
const dataList = ref([
  {
    name: '商户1',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户2',
    code: 'M100002',
    status: false,
  },
  {
    name: '商户3',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户4',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户5',
    code: 'M100001',
  },
  {
    name: '商户6',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户7',
    code: 'M100001',
  },
  {
    name: '商户8',
    code: 'M100002',
    status: true,
  },
  {
    name: '商户9',
    code: 'M100001',
    status: true,
  },
  {
    name: '商户10',
    code: 'M100002',
    status: true,
  },
]);
const handleSwitchChange = (row) => {
  const statusText = row.status ? '启用' : '禁用';
  ElMessage.success(`${statusText}成功`);
  // 这里可以添加状态切换的逻辑，例如发起请求等
};

</script>


<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="" prop="name">
          <el-input v-model="queryParams.keywords" placeholder="商户ID/商户名称/登录账号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="" prop="name">
          <el-input v-model="queryParams.keywords" placeholder="代理ID/代理名称/登录账号" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="" prop="name">
          <el-select v-model="value" clearable placeholder="状态">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
          <el-button type="primary" @click="handleQuery()"><i-ep-search />搜索</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button v-hasPerm="['sys:dict_type:add']" type="success" @click="openDialog()"><i-ep-plus />新增</el-button>
        <el-button v-hasPerm="['sys:dict_type:add']" type="success" @click="openDialog()"><i-ep-plus />通道统一配置</el-button>
        <el-button type="danger" :disabled="ids.length === 0" @click="handleDelete()"><i-ep-delete />批量删除</el-button>
      </template>
      <el-table v-loading="loading" highlight-current-row :data="dataList" border  class="tabs"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="商户ID" prop="name" align="center" min-width="100" fixed />
        <el-table-column label="商户名称" prop="code" align="center" min-width="200" fixed />
        <el-table-column label="登录账号" prop="code" align="left" min-width="150">
          <template #default="scope">
            <div style="display: inline-grid;">
              <span>账户：<span>M100001</span></span>
              <span>谷歌：<span>未绑定</span></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="余额" prop="remark" align="left" min-width="200">
          <template #default="scope">
            <div style="display: inline-grid;">
              <span>余额：¥<span>0.00</span></span>
              <span>冻结：¥<span>0.00</span></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="代付余额" prop="remark" align="left" min-width="200">
          <template #default="scope">
            <div style="display: inline-grid;">
              <span>账户：M100001</span>
              <span>谷歌：<span>未绑定</span></span>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" min-width="100">
          <template #default="{ row }">
            <el-switch v-model="row.status" inline-prompt active-text="启用" inactive-text="禁用"
              @change="handleSwitchChange(row)" />
          </template>
        </el-table-column>
        <el-table-column label="支付产品配置" prop="remark" align="left" min-width="220">
          <template #default="scope">
            <div style="display: flex;">
              <el-button key="primary" type="primary" text bg size="small"
                style="background-color: #e6f7ff;color: #1890ff;border: 1px solid #91d5ff;"
               >支付产品费率</el-button>
              <el-button key="primary" type="primary" text bg size="small"
                style="background-color: #fff0f6;color: #c41d7f;border: 1px solid #ffadd2;"
                >支付通道分流</el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="代付产品配置" prop="remark" align="left" min-width="220">
          <template #default="scope">
            <div style="display: flex;">
              <el-button key="primary" type="primary" text bg size="small"
                style="background-color: #e6fffb;color: #0897b3;border: 1px solid #87e8de;"
                class="product">代付产品费率</el-button>
              <el-button key="primary" type="primary" text bg size="small"
                style="background-color: #f0f5ff;color: #5e39c7;border: 1px solid #adc6ff;"
               >代付通道分流</el-button>
            </div>
          </template>
        </el-table-column>
        <!--        <el-table-column label="代理商ID" prop="remark" align="center" width="200" />-->
        <!--        <el-table-column label="代理商名称" prop="remark" align="center" width="200" />-->
        <el-table-column fixed="right" label="操作" min-width="150">
          <template #default="scope">
            <div style="display: flex;">
              <!-- <el-button type="primary" link size="small" @click.stop="openDictDialog(scope.row)">登录</el-button> -->

              <el-popconfirm title="确定重置该商户密码?" width="230px" >
                <template v-slot:reference="{ confirm }">
                  <el-button type="primary" link size="small" 
                    style="font-size: 16px;">
                    重置密码
                  </el-button>
                </template>
              </el-popconfirm>

              <el-button v-hasPerm="['sys:dict_type:edit']" type="primary" link size="small"
                 style="font-size: 16px;">编辑</el-button>
            </div>
            <div style="display: flex;">
              <el-button type="primary" link size="small" 
                style="font-size: 16px;">对接信息</el-button>
              <el-button v-hasPerm="['sys:dict_type:delete']" type="primary" link size="small"
                @click.stop="handleDelete(scope.row.id)" style="color:red;font-size: 16px;"
                >删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize" @pagination="handleQuery"
        layout="->,total, sizes, prev, pager, next, jumper" />

      <div class="demo-pagination-block" style="float: right;margin-top: 5px;">
        <div class="demonstration"></div>
        <el-pagination v-model:current-page="currentPage4" v-model:page-size="pageSize4"
          :page-sizes="[100, 200, 300, 400]" :small="small" :disabled="disabled" :background="background"
          layout="total, sizes, prev, pager, next, jumper" :total="400" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500px" @close="closeDialog">
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="字典名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典编码" prop="code">
          <el-input v-model="formData.code" placeholder="请输入字典编码" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" type="textarea" placeholder="字典类型备注"
            :autosize="{ minRows: 2, maxRows: 4 }" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!--字典数据弹窗-->
    <el-dialog v-model="dictDataDialog.visible" :title="dictDataDialog.title" width="1000px" @close="closeDictDialog">
      <dict-item v-model:typeCode="selectedDictType.typeCode" v-model:typeName="selectedDictType.typeName" />
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.app-container {
  height: 100%;

  .table-container {
    height: 100%;

    .tabs {
      height: calc(100vh - 260px);
      overflow-y: auto;
    }
  }
}
</style>
